<?php
namespace app\beautiful\helper\payment;
use app\beautiful\logic\PartnerLogic;
use app\common\helper\payment\PaymentBaseHelper;
use app\beautiful\model\order\BuyOrderModel;
use app\beautiful\logic\LogsLogic;
use app\beautiful\model\member\MemberCouponModel;
use app\beautiful\logic\MemberWalletLogic;
use app\common\model\ShopGmvLogsModel;
use app\beautiful\logic\printer\PrinterLogic;

//每个子类只需要专注于自己的 respond 逻辑
class PaymentBuyHelper extends PaymentBaseHelper{
    protected  $moudel = 'beautiful';
    protected  $orderKey = 'mb'; //给一个KEY增大吞吐量
    protected  $respondAction = 'buyRespond';
    
    public function respondCallback($orderId,$payInfo,$fail){
       $order = BuyOrderModel::find($orderId);
       if(null === $order) return;
       if($order->is_paid == 0){ //按道理要做事物
            $order->is_paid  = 1;
            $order->pay_info = $payInfo;
            $order->pay_type = 'weixin';
            $order->pay_time = time();
            $order->save();
            //在线支付的回调不考虑并发情况下优惠券在其他地方的使用 以及积分是否够用了 
            //这些属于后扣除项 所以不准确的去判断了 按逻辑会 给订单做一个事物 主要我们重要的是让别人消费
            if(!empty($order->member_coupon_id)){ //优惠券的使用
                if(null !== $myCoupon = MemberCouponModel::find($order->member_coupon_id)){
                    if($myCoupon->status == 0){
                        $myCoupon->status = 1;
                        $myCoupon->save();
                        LogsLogic::coupon($order->shop_id, $order->member_id, -1, 5, $order->member_coupon_id, '', 0);
                    }
                }
            }
            $MemberWalletLogic = new MemberWalletLogic($order->shop_id, $order->member_id);
            if(!empty($order->use_integral)){ //使用积分
               $MemberWalletLogic->useIntegral($order->use_integral, 6);
            }
            $needPay = round(($order->balance * 100 - $order->vip_balance * 100 - $order->coupon_money * 100 - $order->integral_balance * 100)/100,2);
            $MemberWalletLogic->addIntegralByPayment($needPay); //更新支付返的积分
            
            //分销记录
            $PartnerLogic = new PartnerLogic($order->shop_id);
            $PartnerLogic->commission($order->member_id,$needPay);
            
            //插入日志
            $shop_gmv_logs = new ShopGmvLogsModel();
            $shop_gmv_logs->shop_id=$order->shop_id;
            $shop_gmv_logs->balance=$needPay;
            $shop_gmv_logs->save();

           //打印机
           $printer_logic =new PrinterLogic($order->shop_id);
           $printer_logic->print('buy',$order->buy_order_id);
        }
    }
}